package com.tevintao.marketingsystem.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.tevintao.marketingsystem.commen.RequestManager;
import com.tevintao.marketingsystem.commen.UrlConfig;
import com.tevintao.marketingsystem.log.LogManager;
import com.tevintao.marketingsystem.services.AccountManager;
import com.tevintao.marketingsystem.tool.SystemPathTool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class ChatNewMessageProvider extends ContentProvider {

    private String mAccount = "";


    public static final String KEY_GET_INSERT_JSON = "KEY_GET_INSERT_JSON";

    public ChatNewMessageProvider() {
        if (TextUtils.isEmpty(mAccount)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String newDataPath = AccountManager.MM_DATA_ROOT + "/" + AccountManager.ACCOUNT_NAME_FILE_NAME;
                    mAccount = SystemPathTool.getOutPutContent(newDataPath);
                    LogManager.getInstance().logError("hookResolver query all mAccount = " + mAccount);
                }
            }).start();
        }

    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        return ChatNewChatDB.getInstance().delete(selection, selectionArgs);
    }

    @Override
    public String getType(Uri uri) {
        // TODO: Implement this to handle requests for the MIME type of the data
        // at the given URI.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if (TextUtils.isEmpty(mAccount)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String newDataPath = AccountManager.MM_DATA_ROOT + "/" + AccountManager.ACCOUNT_NAME_FILE_NAME;
                    mAccount = SystemPathTool.getOutPutContent(newDataPath);
                    LogManager.getInstance().logError("hookResolver query all mAccount = " + mAccount);
                }
            }).start();
            return null;
        }

        String jsonArray = values.getAsString(KEY_GET_INSERT_JSON);
        JSONArray newFriend = ChatNewChatDB.getInstance().inertFriend(mAccount, jsonArray);
        LogManager.getInstance().logInfo("加入数据库 数量  newFriend = " + newFriend);
        JSONArray noReportJson = ChatNewChatDB.getInstance().getNoReportFriendJsonArray();
        if (null != noReportJson) {
            LogManager.getInstance().logInfo("未上报好友数量 = " + noReportJson.length());
            LogManager.getInstance().logInfo("未上报好友json = " + noReportJson.toString());
        } else {
            LogManager.getInstance().logInfo("未上报好友数量 = 0");
        }
        checkNoReportFriend();
//        reportNewFriend(newFriend, " 第一次上报 ");
//        Timer timer = new Timer();
//            timer.schedule(new TimerTask() {
//                public void run() {
//                    checkNoReportFriend();
//                }
//        }, 20000);// 设定指定的时间time,此处为2000毫秒

        return null;
    }

    @Override
    public boolean onCreate() {

        return false;
    }


    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        if (TextUtils.isEmpty(mAccount)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    String newDataPath = AccountManager.MM_DATA_ROOT + "/" + AccountManager.ACCOUNT_NAME_FILE_NAME;
                    mAccount = SystemPathTool.getOutPutContent(newDataPath);
                    LogManager.getInstance().logError("hookResolver query all mAccount = " + mAccount);
                }
            }).start();
            return null;
        }
        return ChatNewChatDB.getInstance().getAllMessage(mAccount);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        throw new UnsupportedOperationException("Not yet implemented");
    }


    private void reportNewFriend(final JSONArray jsonArray, final String key) {
        if (null == jsonArray) {
            LogManager.getInstance().logError("null == jsonArray");
            return;
        }
        if (jsonArray.length() == 0) {
            LogManager.getInstance().logError("需要上报好友数量为0");
            return;
        }
        LogManager.getInstance().logInfo(key + " reportNewFriend jsonArray = " + jsonArray.toString());
        if (TextUtils.isEmpty(mAccount)) {
            if (TextUtils.isEmpty(mAccount)) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String newDataPath = AccountManager.MM_DATA_ROOT + "/" + AccountManager.ACCOUNT_NAME_FILE_NAME;
                        mAccount = SystemPathTool.getOutPutContent(newDataPath);
                        LogManager.getInstance().logError("reportNewFriend mAccount = " + mAccount);
                        reportNewFriend(jsonArray, key);
                    }
                }).start();
            }
            return;
        }

        JSONObject jo = new JSONObject();
        try {
            jo.put("friendArray", jsonArray);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String url = String.format(UrlConfig.URL_ADD_NEW_FRIEND, mAccount);
        StringRequest mAddFriend = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                LogManager.getInstance().logInfo(key + " reportNewFriend response = " + response);
                int updateNum = ChatNewChatDB.getInstance().updateFriendFinish(response);
                LogManager.getInstance().logInfo(key + " reportNewFriend updateNum = " + updateNum);
//                ChatNewChatDB.getInstance().disAbleFriend();

                JSONArray noReportJson = ChatNewChatDB.getInstance().getNoReportFriendJsonArray();
                if (null != noReportJson) {
                    LogManager.getInstance().logInfo("未上报好友数量 = " + noReportJson.length());
                } else {
                    LogManager.getInstance().logInfo("未上报好友数量 = 0");
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (null != error && error.getMessage() != null) {
                    LogManager.getInstance().logError("reportNewFriend  error msg =  " + error.getMessage());
                } else {
                    LogManager.getInstance().logError("reportNewFriend  error msg = null ");
                }
            }
        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<>();
                map.put("friendJson", jsonArray.toString());
                return map;
            }

        };
        RequestManager.getInstance().addRequest(mAddFriend);
    }

    private void checkNoReportFriend() {
        JSONArray jsonArray = ChatNewChatDB.getInstance().getNoReportFriendJsonArray();
        if (null == jsonArray || jsonArray.length() == 0) {
            LogManager.getInstance().logInfo("好友已经全部上报");
            return;
        }
        LogManager.getInstance().logInfo("reportNewFriend 未上报好友数量" + jsonArray.length());
        LogManager.getInstance().logInfo("reportNewFriend 未上报好友 Json = " + jsonArray);
        reportNewFriend(jsonArray, " 未上报的好友 ");
    }
}
